import React, { Component } from "react";
import { Alert, Button, Icon, Row, Spin, Col, Badge, Popconfirm, message } from "antd";
import "styles/enterprise-manage/set-of-books-company/legal-person-display-comp.scss";
import LPService from "containers/enterprise-manage/legal-person/legal-person.service";
import { messages } from "share/common";
import FileViewer from "components/file-viewer";
import moment from "moment";
import SlideFrame from "components/slide-frame";
import NewLegalPerson from "containers/enterprise-manage/legal-person/new-legal-person";
import Info from "components/info";

class LegalPersonDisplayComp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showMore: false,
      fileList: [],
      legalPerson: undefined,
      legalPersonList: [],
      headLoading: false,
      listLoading: false,
    };
    this.lanObj = {
      zh_cn: messages("basic-5.key195") /*简体中文*/,
      en: messages("basic-5.key196") /*英文*/,
      ja: messages("basic-5.key197") /*日语*/,
      zh_tw: messages("basic-5.key198") /*繁体中文*/,
      it_it: messages("basic-5.key199") /*意大利语*/,
    };
    this.taxpayerTypeMap = {
      "01": messages("basic-5.key211") /*一般纳税人*/,
      99: messages("basic-5.key212") /*小规模纳税人*/,
    };
    this.infoArray = [
      {
        name: messages("basic-5.key141") /*账套名称*/,
        key: "setOfBooksName",
        render: (value) => {
          return value || "-";
        },
      },
      {
        name: messages("basic-5.key210") /*纳税人识别号*/,
        key: "taxpayerNumber",
        render: (value) => {
          return value || "-";
        },
      },
    ];
    this.otherInfoArray = [
      {
        name: messages("basic-5.key213") /*上级法人*/,
        key: "parentLegalEntityName",
        render: (value) => {
          return value || "-";
        },
      },
      {
        name: messages("basic-5.key214") /*APP开票信息页显示的语言*/,
        key: "mainLanguage",
        render: (value) => {
          return this.lanObj[value.toLowerCase()] || "-";
        },
      },
      {
        name: messages("basic-5.key847") /*法人类型*/,
        key: "legalEntityTypeName",
        render: (value) => {
          return value || "-";
        },
      },
      {
        name: messages("basic-5.key215") /*计税模式*/,
        key: "taxpayerType",
        render: (value) => {
          return this.taxpayerTypeMap[`${value}`] || "-";
        },
      },
    ];
    this.statusInfoArray = [
      {
        name: messages("common.column.status") /*状态*/,
        key: "enable",
        render: (text) => {
          return (
            <span>
              <Badge status={text ? "success" : "error"} />
              {text ? messages("basic-5.key20") /*启用*/ : messages("basic-5.key21") /*禁用*/}
            </span>
          );
        },
      },
    ];
  }

  componentWillMount() {}

  componentDidMount() {
    this.getLegalPersonDetail();
    this.getLegalPersonDetailList();
  }

  componentWillUnmount() {}

  getLegalPersonDetail = () => {
    this.setState({ headLoading: true });
    LPService.getLegalPersonDetail(this.props.params.legalPersonOID).then((res) => {
      const data = res.data;
      if (data.legalEntityAttachmentDTOs && data.legalEntityAttachmentDTOs.length) {
        const fileList = [];
        data.legalEntityAttachmentDTOs.map((attachment) => {
          const num = attachment.filePath.lastIndexOf(".");
          const suffix = attachment.filePath.substr(num);
          fileList.push({
            uid: attachment.attachmentId,
            name: attachment.name + suffix,
            showName: attachment.name,
            status: "done",
            url: attachment.filePath,
          });
        });
        this.setState({ fileList });
      }
      this.setState({
        legalPerson: data,
        headLoading: false,
      });
    });
  };

  getLegalPersonDetailList = () => {
    this.setState({ listLoading: true });
    LPService.getLegalPersonsVersion(this.props.params.legalPersonID)
      .then((res) => {
        if (res.status === 200) {
          this.setState({ legalPersonList: res.data, listLoading: false });
        }
      })
      .catch((err) => {
        this.setState({ listLoading: false });
      });
  };

  handlePreview = (index) => {
    this.setState({ nowIndex: index, show: true });
  };

  renderImages = () => {
    const { nowIndex, show, fileList } = this.state;
    return (
      <div>
        <Row type="flex">
          {fileList.map((attachment, index) => (
            <Col key={index}>
              <div
                onClick={() => this.handlePreview(index)}
                style={{
                  width: 70,
                  height: 70,
                  padding: 5,
                  boxSizing: "border-box",
                  boxShadow: "0 0 3px 1px #e9e9e9",
                  borderRadius: 5,
                  margin: "12px 10px 12px 0",
                  cursor: "pointer",
                  textAlign: "center",
                }}
              >
                <img
                  src={attachment.url}
                  style={{
                    maxHeight: "100%",
                    maxWidth: "100%",
                  }}
                />
              </div>
              <span>{attachment.showName || "-"}</span>
            </Col>
          ))}
        </Row>
        <FileViewer
          attachments={fileList}
          visible={show}
          onCancel={() => this.setState({ show: false })}
          defaultIndex={nowIndex}
        />
      </div>
    );
  };

  renderCardList = () => {
    const { legalPersonList } = this.state;
    const futureList = legalPersonList.filter((item) => item.status === "FUTURE");
    const currentList = legalPersonList.filter((item) => item.status === "CURRENT");
    const pastList = legalPersonList.filter((item) => item.status === "PAST");
    const renderList = [
      {
        list: currentList,
        name: messages("basic-5.key981") /*当前*/,
        key: "CURRENT",
      },
      {
        list: futureList,
        name: messages("basic-5.key950") /*待生效*/,
        key: "FUTURE",
      },
      {
        list: pastList,
        name: messages("basic-5.key951") /*历史*/,
        key: "PAST",
      },
    ];
    return (
      <div className="legal-entity-card-list">
        {renderList.map((type) => {
          if (type.list.length !== 0) {
            return (
              <div className={`single-type ${type.key === "PAST" ? "disabled" : ""}`}>
                <div className="list-title info-text">{type.name}</div>
                {type.list.map((item) => {
                  return this.renderSingleCard(item);
                })}
              </div>
            );
          }
        })}
      </div>
    );
  };

  renderBasicSettingSlide = (config) => {
    const { title, params } = config;
    return {
      title,
      content: NewLegalPerson,
      params,
      afterClose: this.afterClose,
    };
  };

  handleEdit = () => {
    const params = {
      title: messages("basic-5.key220") /*编辑法人实体*/,
      params: {
        legalPersonOID: this.props.params.legalPersonOID,
        onSave: this.getLegalPersonDetail,
        isEdit: true,
      },
    };
    SlideFrame.open(this.renderBasicSettingSlide(params), this);
  };

  addLPDetail = () => {
    const params = {
      title: messages("basic-5.key221") /*新建法人实体信息*/,
      params: {
        legalPersonOID: this.props.params.legalPersonOID,
        legalEntityId: this.props.params.legalPersonID,
        onSave: () => {
          this.getLegalPersonDetailList();
        },
        isEdit: false,
        isNewVersion: true,
      },
    };
    SlideFrame.open(this.renderBasicSettingSlide(params), this);
  };

  editItem = (e, record) => {
    const params = {
      title: messages("basic-5.key222") /*编辑法人实体信息*/,
      params: {
        legalEntityDetailId: record.id,
        legalPersonOID: this.props.params.legalPersonOID,
        onSave: () => {
          this.getLegalPersonDetailList();
        },
        isEdit: false,
        isNewVersion: true,
      },
    };
    SlideFrame.open(this.renderBasicSettingSlide(params), this);
  };

  deleteItem = (e, record) => {
    e.preventDefault();
    LPService.deleteSingleVersion(record.id).then((res) => {
      message.success(messages("common.delete.successful") /*删除成功*/);
      this.getLegalPersonDetailList();
    });
  };

  renderSingleCard = (item) => {
    return (
      <div className="single-info-card">
        <div className="name-and-edit">
          <div className="name">{item.entityName}</div>
          <div className="edit">
            <Popconfirm
              title={messages("common.confirm.delete") /*确定要删除吗？*/}
              onConfirm={(e) => this.deleteItem(e, item)}
            >
              <a className="delete-button">{messages("common.delete") /*删除*/}</a>
            </Popconfirm>
            <span className="ant-divider" />
            <a className="edit-button" onClick={(e) => this.editItem(e, item)}>
              {messages("common.edit") /*编辑*/}
            </a>
          </div>
        </div>
        <Row>
          <Col span={11}>
            {messages("basic-5.key207") /*开户行*/}: {item.accountBank || "-"}
          </Col>
          <Col span={11} offset={1}>
            {messages("basic-5.key208") /*银行卡号*/}: {item.accountNumber || "-"}
          </Col>
        </Row>
        <Row>
          <Col span={11}>
            {messages("basic-5.key174") /*地址*/}: {item.address || "-"}
          </Col>
          <Col span={11} offset={1}>
            {messages("basic-5.key205") /*电话*/}: {item.telephone || "-"}
          </Col>
        </Row>
        <Row>
          <Col span={23}>
            {messages("basic-5.key252") /*有效期起止时间*/}:{" "}
            {
              messages("basic-5.key942", {
                arg1: item.startDate ? moment(item.startDate).format("YYYY/MM/DD") : "-",
                arg2: item.endDate ? moment(item.endDate).format("YYYY/MM/DD") : "-",
              }) /*{arg1} 至 {arg2}*/
            }
          </Col>
        </Row>
      </div>
    );
  };

  render() {
    const { legalPerson, headLoading, listLoading, showMore } = this.state;
    return (
      <div className="legal-person-display-comp">
        <Info
          paragraph
          dataSource={{
            explain: messages("basic-5.key952") /*法人实体信息如有变更可以创建多个信息，但需设置不同的有效期*/,
          }}
          attributes={[{ title: messages("expense-2.key5") /*说明*/, dataIndex: "explain", span: 24, widthFix: false }]}
        />
        <div className="title-box">
          <div className="title-and-btn">
            <div className="legal-person-display-title">{messages("basic-5.key176") /*基础信息*/}</div>
            <Button onClick={this.handleEdit} loading={headLoading}>
              <Icon type="edit" />
              {messages("common.edit") /*编辑*/}
            </Button>
          </div>
        </div>
        <Spin spinning={headLoading}>
          <div className="info-list-box">
            {this.infoArray.map((item) => {
              return (
                <Row>
                  <Col span={6}>{item.name}</Col>
                  <Col span={10} offset={1}>
                    <span className={"info-value"}>{legalPerson ? item.render(legalPerson[item.key]) : "-"}</span>
                  </Col>
                </Row>
              );
            })}
            <div className={`show-hide-div ${showMore ? "show" : ""}`}>
              {this.otherInfoArray.map((item) => {
                return (
                  <Row>
                    <Col span={6}>{item.name}</Col>
                    <Col span={10} offset={1}>
                      <span className={"info-value"}>{legalPerson ? item.render(legalPerson[item.key]) : "-"}</span>
                    </Col>
                  </Row>
                );
              })}
            </div>
            {this.statusInfoArray.map((item) => {
              return (
                <Row>
                  <Col span={6}>{item.name}</Col>
                  <Col span={10} offset={1}>
                    <span className={"info-value"}>{legalPerson ? item.render(legalPerson[item.key]) : "-"}</span>
                  </Col>
                </Row>
              );
            })}
          </div>
          {showMore && (
            <div className="img-list-box">
              <Row>
                <Col span={6}>
                  <div className="">{messages("basic-5.key223") /*开票二维码*/}</div>
                </Col>
                <Col span={14} offset={1}>
                  <span className={"info-value"}>
                    {legalPerson &&
                    legalPerson.legalEntityAttachmentDTOs &&
                    legalPerson.legalEntityAttachmentDTOs.length !== 0 ? (
                      this.renderImages((legalPerson && legalPerson.legalEntityAttachmentDTOs) || [])
                    ) : (
                      <div>{messages("basic-5.key247") /*无开票二维码*/}</div>
                    )}
                  </span>
                </Col>
              </Row>
            </div>
          )}
          <div
            className="show-switch"
            onClick={() => {
              this.setState({ showMore: !showMore });
            }}
          >
            {showMore ? messages("common.fold") /*收起*/ : messages("basic-5.key953") /*展开*/}
            <Icon
              type="down"
              style={{
                transitionDuration: ".3s",
                transform: showMore ? "rotate(-180deg)" : "unset",
              }}
            />
          </div>
        </Spin>
        <Spin spinning={listLoading}>
          <div className="entity-info-box">
            <div className="legal-person-display-title">{messages("basic-5.key224") /*法人实体信息*/}</div>
            <Button type="dashed" onClick={this.addLPDetail}>
              <Icon type="plus" />
              {messages("basic-5.key954") /*新增法人实体信息*/}
            </Button>
            {this.renderCardList()}
          </div>
        </Spin>
      </div>
    );
  }
}

export default LegalPersonDisplayComp;
